<script setup lang="ts">
import { supplyTypeMap } from './enums'
import * as DinePrintConfigApi from '@/api/dine/print/DinePrintConfigApi'
import { checkRole } from '@/utils/permission'

defineComponent({
  name: 'DinePrintConfigForm'
})

const formRef = ref()

// 表单数据模型
const formData = ref<any>({
  id: undefined,
  supplyType: 1,
  printerName: '',
  printerSn: '',
  printerKey: ''
})

// 表单验证规则
const rules = {
  supplyType: [{ required: true, message: '请选择打印机厂商', trigger: 'change' }],
  printerName: [{ required: true, message: '请输入打印机名称', trigger: ['change', 'blur'] }],
  printerSn: [{ required: true, message: '请输入打印机唯一标识', trigger: ['change', 'blur'] }],
  printerKey: [{ required: true, message: '请输入打印机秘钥', trigger: ['change', 'blur'] }]
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      DinePrintConfigApi.write(formData.value)
    }
  })
}

const formLoading = ref(false)
const loadConfig = async () => {
  formLoading.value = true
  try {
    formData.value = await DinePrintConfigApi.read()
  } finally {
    formLoading.value = false
  }
}
onMounted(async () => {
  if (checkRole(['shop_admin'])) {
    await loadConfig()
    return
  }
})
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="100px"
    label-position="right"
    v-loading="formLoading"
  >
    <el-form-item label="厂商" prop="supplyType">
      <el-radio-group v-model="formData.supplyType">
        <el-radio
          v-for="(item, index) in supplyTypeMap"
          :key="index"
          :value="Number(index)"
          :disabled="Number(index) !== 1"
        >
          {{ item }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="名称" prop="printerName">
      <el-input
        v-model="formData.printerName"
        placeholder="打印机名称，如：前台收银打印机"
        clearable
      />
    </el-form-item>
    <el-form-item prop="printerSn">
      <template #label>
        <Tooltip
          title="标识(SN)"
          message="打印机标识，具体可查看飞鹅云打印机的机身背面带“SN”字样的标签"
        />
      </template>
      <el-input
        v-model="formData.printerSn"
        placeholder="打印机唯一标识，如：332107118"
        clearable
      />
    </el-form-item>
    <el-form-item label="秘钥(KEY)" prop="printerKey">
      <template #label>
        <Tooltip
          title="秘钥(KEY)"
          message="打印机秘钥，具体可查看飞鹅云打印机的机身背面带“KEY”字样的标签"
        />
      </template>
      <el-input v-model="formData.printerKey" placeholder="打印机秘钥，如：gMHB4aRz" clearable />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm" :loading="formLoading">保存</el-button>
    </el-form-item>
  </el-form>
</template>
